<script setup>
import { computed, ref, watch, nextTick, toRefs, reactive } from "vue";
import request from "@/common/utils/request";
import store from "@/store/index";
import { ArrowRightOutlined } from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import utils from "@/common/utils/utils";
import { message, Modal } from "ant-design-vue";
import LoginModal from "../../../components/LoginModal/index.vue";

import dayjs from "dayjs";
const route = useRoute();
const router = useRouter();
const aiTxt = ref("");
const config = ref(null);
const aiConfig = ref(null);
const applicationGroupList = ref([]);
const industryGroupList = ref([]);
const loginVisible = ref(false);
const promptReplaceVisible = ref(false);
const iframeContainerVisible = ref(false);
const iframeLoaded = ref(false);
const currentPrompt = ref({});
const collectApps = ref([]);
const activeKey = ref(null);
const dataList = ref([]);
const dataSource = ref([]);
const collectAppIds = computed(() => {
  return collectApps.value.map((app) => app.id);
});

const state = reactive({
  total: 0,
  page: 1,
  pageSize: 10,
  dateTime: undefined,
  application_id: undefined,
  loading: false,
});

let columns = [
  {
    title: "序号",
    dataIndex: "id",
    key: "id",
    width: 100,
  },
  {
    title: "标题",
    dataIndex: "title",
    key: "title",
    ellipsis: true,
  },
  {
    title: "生成内容",
    dataIndex: "content",
    key: "content",
    ellipsis: true,
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 100,
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    key: "created_at",
    width: 200,
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: 240,
    align: "center",
  },
];

const pagination = computed(() => ({
  total: state.total,
  current: state.page,
  pageSize: state.pageSize,
  showSizeChanger: true,
  showTotal: (total) => `共${total}条`,
}));

const getCategoryList = async () => {
  const { applicationList, industryList } = await store.dispatch(
    "GetSceneApps"
  );
  let filterList = applicationList.filter((item) => item.is_social_media == 0);
  applicationGroupList.value = [].concat(filterList);

  industryGroupList.value = industryList;
  if (route.query?.appId) {
    activeKey.value = route.query?.appId;
  } else {
    activeKey.value = filterList?.[0]?.id;
  }
};

const getCategoryDetails = () => {
  const categoryId = activeKey.value;
  request
    .get("/work_ai", "/application/category/app_list", {
      is_industry: 0,
      cat_id: categoryId,
      is_social_media: 0,
    })
    .then(({ app_list }) => {
      dataList.value = app_list;
    });
};

const getTableList = () => {
  state.loading = true;
  let application_category_id = dataList.value.find(
    (item) => item.id == state.application_id
  )?.cat_id;
  const params = {
    page: state.page,
    pageSize: state.pageSize,
    application_category_id,
    application_id: state.application_id,
  };

  if (state.dateTime) {
    params.created_start_time = dayjs(state.dateTime?.[0]).format("YYYY-MM-DD");
    params.created_end_time = dayjs(state.dateTime?.[0]).format("YYYY-MM-DD");
  }
  request
    .get("/work_ai", "/user/socialMedia/campaignTaskLog/list", params)
    .then((res) => {
      dataSource.value = res.list;
      state.total = res?.total;
      state.loading = false;
    })
    .catch(() => {
      state.loading = false;
    });
};

watch(
  () => activeKey.value,
  (val) => {
    if (val) {
      state.application_id = undefined;
      getCategoryDetails();
      getTableList();
    }
  },
  {
    immediate: true,
  }
);

const getUserCollectApps = async () => {
  const { data } = await request.get("/work_ai", "/user/collect/list", {
    type: "application",
  });
  collectApps.value = data.map((item) => item.collectable);
};

const initData = async () => {
  if (route.query.appId) {
    if (route.path.includes("socialMedia")) {
      router.push(
        `/socialMedia/ContentGeneration/multifunctionWrite?cate_id=${route.query.cateId}&app_id=${route.query.appId}`
      );
    } else {
      router.push({
        name: "SceneCreation",
        query: {
          cateId: route.query.cateId,
          appId: route.query.appId,
        },
      });
    }
    return;
  }

  const configInfo = await store.dispatch("GetConfigInfo");
  const system_name = configInfo?.basic?.system_name;

  if (system_name && system_name.slice(-2) && system_name.slice(-2) == "AI")
    aiTxt.value = system_name.slice(-2);

  config.value = configInfo;
  console.log("config.value", config.value);

  const aiConfigInfo = await store.dispatch("getAiConfig");
  aiConfig.value = aiConfigInfo;

  await getCategoryList();

  // const isLogin = await utils.checkLogin();

  // if (isLogin) {
  //   await getUserCollectApps();
  // }
};

initData();

const onAppClick = (item) => {
  router.push({
    name: "SceneCreation",
    query: {
      cateId: item.cat_id,
      appId: item.id,
    },
  });
};

const onCollectClick = (app) => {
  utils.checkLogin().then((isLogin) => {
    if (!isLogin) {
      loginVisible.value = true;
      return;
    }

    const status = collectAppIds.value.includes(app.id) ? 0 : 1;

    request
      .post("/work_ai", "/user/collect", {
        collect_type: "application",
        collect_id: app.id,
        status,
      })
      .then(() => {
        if (status) {
          collectApps.value.push(app);
        } else {
          collectApps.value = collectApps.value.filter(
            (item) => item.id !== app.id
          );
        }
      });
  });
};

const handleTableChange = (pager) => {
  state.page = pager.current;
  state.pageSize = pager.pageSize;
  getTableList();
};

const handleSearch = () => {
  state.page = 1;
  getTableList();
};

// 使用提示词

const replaceCallback = async (list) => {
  if (list && list.length > 0) {
    list.forEach((item) => {
      currentPrompt.value.content = currentPrompt.value.content.replace(
        item[0],
        item[1]
      );
    });

    const chat_id = await addChatByMessage(currentPrompt.value.content);
    router.push(
      `/chatModel/chat?chat_id=${chat_id}&message=${currentPrompt.value.content}`
    );
  }
};

const addChatByMessage = async (message) => {
  const params = {
    title: message.value,
    team_id: utils.getCurrentTeam() || 0,
  };

  const { chat_id } = await request.post("/work_ai", "/chat/add", params);

  return chat_id;
};

const promptReplaceClose = () => {
  promptReplaceVisible.value = false;
  currentPrompt.value = {};
};

const loginCallback = () => {
  loginVisible.value = false;
  router.go(0);
};

const openUrl = (url) => {
  window.open(url, "_blank");
};

watch(iframeContainerVisible, (visible) => {
  if (visible && !iframeLoaded.value) {
    nextTick(() => {
      iframeLoaded.value = true;
    });
  }
});
// 去创作
const goToArticle = (record) => {
  router.push({
    name: "TextImitation",
    query: {
      AIsceneCenterId: record.id,
    },
  });
};
const preview = (record) => {
  router.push({
    name: "SceneCreation",
    query: {
      id: record.id,
    },
  });
};
const onDeleteClick = (id, campaign_task_id) => {
  Modal.confirm({
    title: "确定要删除该篇文章吗?",
    okText: "确定",
    cancelText: "取消",
    onOk() {
      request
        .del("/work_ai", "/user/socialMedia/campaignTaskLog/delete", {
          ids: [id],
          campaign_task_id,
        })
        .then((res) => {
          message.success("删除成功");
          state.page = 1;
          getTableList();
        });
    },
  });
};
</script>

<template>
  <div class="page-warp">
    <div class="app-tab">
      <!-- 标题 -->
      <div class="flex align-center mb-20">
        <RouteTitle :isBack="$route?.query?.key" />
        <span class="pt-5 ml-5 text-12 text-gray-6"
          >多应用场景文案自动生成</span
        >
      </div>
      <!-- tab栏 -->
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane
          v-for="item in applicationGroupList"
          :key="item.id"
          :tab="item.cat_name"
        ></a-tab-pane>
      </a-tabs>
      <!-- 应用列表 -->
      <div class="app-section">
        <div class="app-section__list">
          <div
            class="app-card"
            v-for="(app, index) in dataList"
            :key="index"
            @click="onAppClick(app)"
          >
            <div class="flex align-center">
              <div class="app-card__image">
                <img :src="app.icon" />
              </div>
              <div class="app-card__title">
                {{ app.name }}
              </div>
            </div>
            <div class="app-card__info">
              {{ app.info }}
            </div>
            <div class="app-card__icon" @click.stop="onCollectClick(app)">
              <CuIcon
                class="app-card__icon--shoucang"
                :type="
                  collectAppIds.includes(app.id)
                    ? 'icon-shoucang2'
                    : 'icon-shoucang'
                "
              />
            </div>
            <svg
              class="app-card__arrow"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="8946"
              id="mx_n_1706164826887"
              xmlns:xlink="http://www.w3.org/1999/xlink"
              width="24"
              height="24"
            >
              <path
                d="M25.536 512c0 268.672 217.728 486.4 486.4 486.4s486.4-217.728 486.4-486.4S780.608 25.6 511.936 25.6A486.4 486.4 0 0 0 25.536 512z m576.128-202.496l184.32 184.384a25.344 25.344 0 0 1 0 36.224l-184.32 184.32a25.6 25.6 0 0 1-36.224-36.224l140.672-140.672H255.936a25.6 25.6 0 1 1 0-51.2h450.176L565.44 345.664a25.6 25.6 0 0 1 36.224-36.224z"
                p-id="8947"
                fill="#2878ff"
              ></path>
            </svg>
          </div>
        </div>
      </div>
    </div>
    <div class="mt-40 app-tab">
      <p class="fs-14 font-bold">生成记录</p>
      <a-card>
        <a-space :size="20" class="mb-20">
          <a-space>
            创作时间：<a-range-picker
              v-model:value="state.dateTime"
              allowClear
            />
          </a-space>
          <a-space>
            应用：
            <a-select
              style="width: 200px"
              v-model:value="state.application_id"
              placeholder="请选择当前分类下的应用"
              allowClear
              :options="
                dataList?.map((item) => ({
                  label: item.name,
                  value: item.id,
                }))
              "
            >
            </a-select>
          </a-space>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
          </a-space>
        </a-space>
        <a-table
          :dataSource="dataSource"
          :columns="columns"
          :loading="state.loading"
          :pagination="pagination"
          @change="handleTableChange"
          rowKey="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'title'">
              {{ record.title ? record.title : "--" }}
            </template>
            <template v-if="column.key === 'content'">
              <div
                class="text-overflow"
                :title="record.content"
                v-if="record.content"
              >
                {{ record.content }}
              </div>
              <div v-else>--</div>
            </template>
            <template v-if="column.key === 'status'">
              <a-tooltip v-if="record.status == 3">
                <template #title>{{ record.status_msg }}</template>
                <span style="color: red">{{ record.status_txt }}</span>
              </a-tooltip>
              <span v-else style="color: green">{{ record.status_txt }}</span>
            </template>
            <template v-if="column.key === 'action'">
              <a-button
                type="link"
                @click="goToArticle(record)"
                :disabled="record.status == 3 || record.status == 1"
                >去创作</a-button
              >
              <a-button
                type="link"
                @click="preview(record)"
                :disabled="record.status == 3 || record.status == 1"
                >查看</a-button
              >
              <a-button
                type="link"
                danger
                class="mr-10"
                :disabled="record.status == 1"
                @click="onDeleteClick(record.id, record.campaign_task_id)"
              >
                删除
              </a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
    <div
      class="additional-info"
      v-if="(config && config.basic) || (aiConfig && aiConfig.about_url)"
    >
      <template v-if="config && config.basic">
        <span
          style="margin-right: 10px"
          @click="openUrl('https://beian.miit.gov.cn/')"
          v-if="config.basic.system_domain_icp"
          >{{ config.basic.system_domain_icp }}</span
        >
        <span
          style="margin-left: 10px; margin-right: 10px"
          @click="openUrl('http://www.beian.gov.cn/ ')"
          v-if="config.basic.system_domain_police"
          >{{ config.basic.system_domain_police }}</span
        >
      </template>
      <template v-if="aiConfig && aiConfig.about_url">
        <span style="margin-left: 10px" @click="openUrl(aiConfig.about_url)"
          >关于我们</span
        >
      </template>
    </div>

    <template v-if="aiConfig && aiConfig.bubble_image && aiConfig.bubble_url">
      <div
        v-show="iframeContainerVisible"
        v-if="iframeContainerVisible || iframeLoaded"
        id="iframe_container"
        style="
          position: fixed;
          right: 4vmin;
          bottom: calc(4vmin + 68px + 2vmin);
          z-index: 999999;
          width: 520px;
          height: 80vmin;
          border: 1px solid #dcdfe6;
          border-radius: 15px;
        "
      >
        <div
          class="close-icon"
          style="
            position: absolute;
            right: -10px;
            top: -10px;
            height: 30px;
            width: 30px;
            text-align: right;
            color: #7b9efb;
            cursor: pointer;
            background-color: rgba(232, 234, 247, 0.6);
            border-radius: 50%;
            display: none;
            padding: 6px;
          "
          @click="iframeContainerVisible = false"
        >
          <svg
            viewBox="0 0 1024 1024"
            xmlns="http://www.w3.org/2000/svg"
            data-v-ea893728=""
          >
            <path
              fill="currentColor"
              d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z"
            ></path>
          </svg>
        </div>
        <iframe
          id="iframe_cby"
          :src="aiConfig.bubble_url"
          style="
            width: 100%;
            height: 100%;
            border: none;
            border-radius: 15px;
            overflow: hidden;
          "
        ></iframe>
      </div>
    </template>
    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />
  </div>
</template>

<style lang="less" scoped>
.page-warp {
  // width: 100%;
  // height: 100%;
  // overflow: hidden auto;

  :deep(.ss-tabs-nav) {
    margin-bottom: 0;
  }
  .tag {
    width: 100%;
    display: flex;
    justify-content: left;
    align-items: center;
    padding: 3px 0px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    border: none;
    margin-bottom: 15px;
    margin-top: -20px;

    .horn {
      width: 30px;
      height: 30px;
      object-fit: cover;
      margin-right: 5px;
    }
    .close-circle {
      background: #867d7b;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      color: #f4f5ff;
      font-size: 26px;
    }
    .favorite-tips-box {
      padding: 3px 5px;
      background: #e9ebec;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
      color: #6965ea;
      margin: 0 5px;
    }

    .container {
      width: 100%;
      height: 25px;

      .marquee {
        width: 100%;
        height: 25px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        .image {
          margin-right: 8px;
          display: inline-block;
          width: 20px;
          height: 20px;
          line-height: 20px;
          object-fit: cover;
          margin-bottom: 3px;
        }
      }
    }
    :deep(.slick-list) {
      height: 30px;
    }
    :deep(.slick-slide) {
      height: 30px;
    }
  }
}

.workbenches-box {
  background-color: #ac85f3;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  padding: 40px 0px 30px;
  color: #ffffff;
  border-radius: 10px;
}

.page-title {
  font-size: 36px;
  font-weight: 700;
}

.page-subtitle {
  font-size: 16px;
}

.search-box {
  border-radius: 20px;
  background: linear-gradient(to right, #e4dbfd, #deedfe);
  padding: 4px;

  .search-prefix-icon {
    display: none;
    padding: 0px 8px 0px 10px;
    font-weight: bold;
    color: #7a46fc;
    font-size: 20px;
    background: linear-gradient(
      47deg,
      #6554ff 0%,
      #f26dbe 57.0068359375%,
      #febd7f 91.357421875%
    );
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .search-input {
    background: #ffffff;
    border-radius: 20px;
    padding: 3px;
    padding-right: 10px;

    &__prefix {
      color: #a27dfd;
      font-size: 12px;
      background: #efe9ff;
      border-top-left-radius: 20px;
      border-bottom-left-radius: 20px;
      height: 26px;
      line-height: 26px;
      padding: 0px 10px 0px 12px;
      cursor: pointer;
    }

    input {
      border: none;
      outline: none;
      width: 320px;
      font-size: 13px;
      margin-left: 5px;
      padding: 0px 10px;

      &:focus {
        border: none;
        box-shadow: none;
      }
    }
  }

  .search-btn {
    background: #ff8986;
    border: 2px solid #fff;
    padding: 3px 7px;
    border-radius: 16px;
    font-size: 13px;
    height: 100%;
    cursor: pointer;
  }
}

.category-box {
  &__item {
    margin-right: 30px;
    cursor: pointer;

    &:last-child {
      margin-right: 0px;
    }
  }

  &__image {
    width: 32px;
    height: 32px;

    img {
      height: 100%;
      width: 100%;
      border-radius: 50%;
      object-fit: cover;
    }
  }

  &__title {
    font-size: 12px;
    margin-top: 5px;
  }
}

.app-section {
  margin-top: 20px;

  // &:first-child .app-section__list {
  //     grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
  // }

  &__title {
    font-size: 16px;
    font-weight: 700;
  }

  &__list {
    margin-top: 15px;
    display: grid;
    gap: 20px;
    grid-template-columns: repeat(5, minmax(0, 1fr));

    .app-card {
      border-radius: 10px;
      background: #fff;
      border: 1px solid #e9e9e9;
      width: 100%;
      padding: 20px 16px 30px;
      cursor: pointer;
      position: relative;
      transition: all 0.3s;

      &__image {
        width: 40px;
        height: 40px;
        border: 1px solid rgba(0, 0, 0, 0.04);
        padding: 3px;
        border-radius: 32% !important;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 32% !important;
        }
      }

      &__title {
        margin-left: 10px;
        font-size: 16px;
        font-weight: 600;
        transition: all 0.3s;
      }

      &__info {
        margin-top: 20px;
        color: #767676;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      &__icon {
        position: absolute;
        right: 15px;
        top: 10px;
        display: none;

        &--shoucang {
          font-size: 16px;
        }
      }

      &__arrow {
        color: var(--ss-primary-color);
        position: absolute;
        right: 15px;
        bottom: 10px;
        font-size: 20px;
        visibility: hidden;
        opacity: 0;
        transition: all 0.3s;
      }

      &:hover {
        -webkit-transform: translateY(-3px);
        -ms-transform: translateY(-3px);
        transform: translateY(-3px);

        .app-card__title {
          color: var(--ss-primary-color);
        }

        .app-card__arrow {
          visibility: visible;
          opacity: 1;
        }

        .app-card__icon {
          display: block;
        }
      }
    }
  }
}

.additional-info {
  margin-top: 30px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  span {
    color: #bbb;
    cursor: pointer;

    &:hover {
      color: @primary-color;
    }
  }
}

@media (min-width: 1024px) {
  .app-section {
    &__list {
      grid-template-columns: repeat(4, minmax(0, 1fr));
    }
  }
}

@media (min-width: 1280px) {
  .app-section {
    &__list {
      grid-template-columns: repeat(5, minmax(0, 1fr));
    }
  }
}

@media (min-width: 1536px) {
  .app-section {
    &__list {
      grid-template-columns: repeat(6, minmax(0, 1fr));
    }
  }
}

#iframe_container:hover {
  .close-icon {
    display: block !important;
  }
}
.text-overflow {
  width: 100%;
  // 两行省略
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: normal;
  max-height: 40px;
}
</style>
